package org.utils.xml.xmlupdater;

import org.apache.log4j.Logger;
import org.utils.common.InitException;
import org.utils.xml.XMLDataNode;

/**
 * How to use this XmlUpdater.
 * Here is a xml configuration file example showing how to use this updater.
 * <pre>
 * 	  &lt;XmlUpdater&gt;
 *        	  &lt;Defines&gt;
 *			  &lt;define name="var1" type="const" value="toto" /&gt;
 *			  &lt;define name="var2" type="const" value="6849" /&gt;
 *			  &lt;define name="var3" type="const" value="SampleValue" /&gt;
 *		  &lt;/Defines&gt;
 *		  &lt;Rules&gt;
 *			  &lt;Update field="root.child1.child11[att1]" with="${var2}:${var2}" /&gt;
 *			  &lt;Update field="root.child1.child11" with="notaconstant" /&gt;
 *			  &lt;Update field="root.child2" with="${var3}" /&gt;
 *		  &lt;/Rules&gt;
 *	  &lt;/XmlUpdater&gt;
 * </pre>
 * In the first part, represented by the tag &lt;Defines&gt; you can define
 * constants that represents common values.
 * In the second part, you define the field or attributes to be update using
 * the value of zero or various constants previously defined.
 * Then you instantiate an XmlUpdater Object with this configuration (using the
 * XMLDataNode Object) and further call the applyRules() method with the xml to
 * update and get the result as a return of this method call.
 *
 * @author  Manuel EVENO
 * @version 1.0
 *
 * @see DefinesHandler
 * @see RulesHandler
 */
public class XmlUpdater
{
  private boolean configured = false;
  /**
   * Creates a new XmlUpdater
   */
  public XmlUpdater()
  {
  }

  /**
   * Creates a new XmlUpdater
   */
  public XmlUpdater(XMLDataNode config) throws InitException
  {
    if (config != null)
      init(config);
  }

  public void init(XMLDataNode config) throws InitException
  {
//    if (config.getChild("Defines") == null)
//       throw new InitException("Missing tag <Defines> in the rules document");
    DefinesHandler.init(config.getChild("Defines"));
    RulesHandler.init(config.getChild("Rules"));
    Logger.getLogger(this.getClass()).debug( DefinesHandler.getInstance().toString() );
    Logger.getLogger(this.getClass()).debug( RulesHandler.getInstance().toString() );
    configured = true;
  }

  /**
   * Launch the update of the xml hierarchy given in parameter
   * @param root The hierarchy to update
   */
  public XMLDataNode applyRules(XMLDataNode root) throws InitException
  {
    if (configured)
      return RulesHandler.getInstance().applyRules(root);
    return root;
  }
}
